<template>
  <div class="create-ip-order">
    <Title title="订单信息" class="mb-16" />
    <div class="create-ip-order-form">
      <el-form
        ref="formRef"
        :model="paramsObj"
        :rules="rules"
        label-position="right"
        class="edit-order lineHeight32"
        label-width="90px">
        <div class="one-cell color999">
          <el-form-item label="订单类型" prop="orderType" style="margin-bottom:20px;">营销授权</el-form-item>
        </div>
        <div class="one-cell">
          <el-form-item style="margin-right: 108px;" label="IP形象" prop="ipAry">
            <div>
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.ipAry"
                :select-data-list="paramsObj.ipAry || []"
                :hide-select-list="paramsObj.ipAry || []"
                :loadmore-method="getipFigure()"
                multiple
                style="width:240px;"
                placeholder="请选择IP形象"
                value-type="object"
                key-name="ipId"
                extend-class="create-ip-order-select"
                label-name="ipNameAndSeries"
                filterable
                collapse-tags
                clearable
                @change="ipFigureChange"
              />
            </div>
          </el-form-item>
          <el-form-item label="客户名称" prop="clientName" style="">
            <selectWithUserLoad
              ref="selectUser"
              v-model="paramsObj.clientObj"
              :hide-select-list="paramsObj.clientObj && JSON.stringify(paramsObj.clientObj) !== '{}' ?[paramsObj.clientObj] : []"
              :select-data-list="paramsObj.clientObj && JSON.stringify(paramsObj.clientObj) !== '{}' ?[paramsObj.clientObj] : []"
              :multiple="false"
              :loadmore-method="getClient()"
              style="width:240px;"
              placeholder="请选择客户"
              extend-class="create-ip-order-select"
              value-type="object"
              key-name="id"
              label-name="clientName"
              filterable
              collapse-tags
              clearable
              @change="clientNameChange"
            />
          </el-form-item>
        </div>
        <div class="left">
          <el-form-item label="销售" prop="market" style="">
            <selectWithUserLoad
              ref="selectUser"
              v-model="paramsObj.marketObj"
              :hide-select-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
              :select-data-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
              :multiple="false"
              style="width:240px;"
              placeholder="请选择销售"
              value-type="object"
              key-name="id"
              label-name="userName"
              extend-class="create-ip-order-select"
              filterable
              collapse-tags
              @change="marketChange"
            />
          </el-form-item>
          <el-form-item label="含税金额" prop="taxAmount" style="">
            <el-input
              v-model="paramsObj.taxAmount"
              disabled
              oninput="if(value>999999999)value=999999999;"
              name="minPrice"
              type="number"
              placeholder="=收入项+IP授权费"
              size="small"
              @change="numberInputChange('taxAmount')"
              @mousewheel.native.prevent
            />
          </el-form-item>
          <!-- <el-form-item label="创意物料费" prop="materielPrice" style="">
            <el-input
              v-model="paramsObj.materielPrice"
              :disabled="true"
              oninput="if(value>999999999)value=999999999;"
              name="materielPrice"
              type="number"
              placeholder="=含税金额-IP授权费"
              size="small"
              @mousewheel.native.prevent
            />
          </el-form-item> -->
          <el-form-item label="交付时间" prop="deliveryTime">
            <el-date-picker
              v-model="paramsObj.deliveryTime"
              :clearable="true"
              :editable="false"
              type="date"
              placeholder="请选择交付时间"
              value-format="timestamp"
              size="small"
              class="order-time"
              format="yyyy/MM/dd"/>
          </el-form-item>
          <el-form-item label="附件" prop="attachment" class="attachment">
            <div class="attachment-container" style="width: 240px;">
              <!-- /admin/mengli/order/file/upload -->
              <upAttachment
                ref="uploadImg"
                :import-api="'/admin/mengli/order/file/upload'"
                :hide-confirm="true"
                :file-list="paramsObj.attachment"
                btn-text="上传文件"
                @upProgress="upProgress"
                @complateSetData="complateSetData"
                @removeFileList="removeFileList" />
            </div>
          </el-form-item>
        </div>
        <div class="right">
          <el-form-item label="下单日期" prop="orderTime">
            <el-date-picker
              v-model="paramsObj.orderTime"
              :clearable="false"
              :editable="false"
              type="date"
              placeholder="请选择下单日期"
              value-format="timestamp"
              size="small"
              class="order-time"
              format="yyyy/MM/dd"/>
          </el-form-item>
          <el-form-item label="IP授权费" prop="licensePrice" style="">
            <el-input
              v-model="paramsObj.licensePrice"
              oninput="if(value>999999999)value=999999999;"
              name="licensePrice"
              type="number"
              placeholder="IP授权费"
              size="small"
              @blur="numberInputChange('licensePrice')"
              @mousewheel.native.prevent
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark" style="">
            <el-input v-model="paramsObj.remark" placeholder="备注" maxlength="200" name="remark" type="text" size="small" />
          </el-form-item>
          <el-form-item label="标签" prop="tag">
            <TagSelect v-model="paramsObj.tag" :collapse-tags="false" :module-type="TAG_MODULES.MARKET_AUTH"/>
          </el-form-item>
        </div>
      </el-form>
      <IncomeItem
        v-if="hasRouteAuth('mengli:emojiOrder:incomeRead') || hasRouteAuth('mengli:emojiOrder:incomeAdmin') || isAdmin"
        v-model="paramsObj.incomeList"
        :has-add-auth="hasRouteAuth('mengli:emojiOrder:incomeAdd') || isAdmin"
        :has-edit-auth="hasRouteAuth('mengli:emojiOrder:incomeEdit') || isAdmin"
        :has-delete-auth="hasRouteAuth('mengli:emojiOrder:incomeDelete') || isAdmin"
        :is-detail="isEdit"
        @changeValue="mathTaxAmount"
        @editIcomeItem="editIcomeItem"
        @addIcomeItem="addIcomeItem"
        @deleteIcomeItem="deleteIcomeItem"
      />
      <!-- <Title title="分成信息" />
      <ipSupplier ref="ipSupplier" /> -->
      <costBreakdownComponent
        ref="costBreakdownRef"
        :is-create="!isEdit"
        :order-id="orderId"
        :cost-belong-type="3"
        :is-mengli="true"
        :is-detail="false"/>
      <div class="select-related-container" style="margin-top: 40px;">
        <InvoiceAndContract
          ref="ContractSelect"
          :show-empty="true"
          :is-edit="true"
          :title="'合同信息'"
          :sub-title="'关联合同'"
          :type="1"
          style="margin-top: 10px;"
          placeholder="请输入合同编号/合同名称" />
      </div>
      <div class="select-related-container">
        <InvoiceAndContract
          ref="InvoiceSelect"
          :is-edit="true"
          :show-empty="true"
          :title="'发票信息'"
          :sub-title="'关联发票'"
          :is-disabled="false"
          :type="2"
          show-invoice-amount-total
          style="margin-top: 10px;"
          target-keyword="no"
          placeholder="请输入发票编号/发票号码" />
      </div>
      <fixed-pagination>
        <div class="center">
          <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存订单</el-button>
          <el-button type="info" size="small" class="cancel-btn-style" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import {
  getIpImageList, getClientList,
  createEmojiOrder, editEmojiOrder, getEmoji,
  addEmojiIncomeList, editEmojiIncomeList, deleteEmojiIncomeList
} from '@/api/mengliOrder';
import { validateIp, validateTime, validateNumber } from './validator/validator';
import upAttachment from '@/components/Common/upAttachment/index';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
// import ipSupplier from '@/components/Mengli/mengliOrder/createMengli/ipSupplier';
import costBreakdownComponent from '@/components/CreateOrder/costList';
import IncomeItem from '@/components/Mengli/mengliOrder/incomeItem/index';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import TagSelect from '@/components/Common/tagSelect';

export default {
  components: { TagSelect, IncomeItem, Title, selectWithUserLoad, selectWithoutHttp, upAttachment, costBreakdownComponent, InvoiceAndContract },
  data() {
    return {
      TAG_MODULES,
      isEdit: false,
      btnLoading: false,
      taxAmountDisabled: false,
      orderId: '',
      orderType: '',
      paramsObj: {
        ipAry: [],
        orderTime: new Date().setHours(0, 0, 0, 0),
        market: '', // 销售
        marketId: '', // 销售id
        marketObj: {},
        clientName: '',
        clientId: '',
        clientObj: {},
        deliveryTime: '',
        area: '',
        remark: '',
        taxAmount: '',
        licensePrice: '',
        materielPrice: '',
        attachment: [],
        incomeList: [],
        tag: []
      },
      rules: {
        orderTime: [{ required: true, trigger: 'change', validator: validateTime('请选择下单日期') }],
        ipAry: [{ required: true, trigger: 'change', validator: validateIp('请选择IP形象') }],
        market: [{ required: true, trigger: 'change', validator: validateIp('请选择销售') }],
        clientName: [{ required: true, trigger: 'change', validator: validateNumber('请选择客户名称') }],
        licenseTime: [{ required: true, trigger: 'change', validator: validateTime('请选择下单日期') }],
        licensePrice: [{ required: true, trigger: 'change', validator: validateNumber('请输入IP授权费') }]
      }
    };
  },
  computed: {
    ipSeriesName() {
      const ipAry = this.paramsObj.ipAry;
      const name = [];
      if (ipAry && ipAry.length) {
        ipAry.forEach(i => {
          name.push(i.ipSeries);
        });
      }
      return name.join(',');
    },
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
    this.orderId = this.$route.params.id || '';
    this.orderType = this.$route.query.type || '0';
    if (this.orderId) {
      this.isEdit = true;
      this.getDetail();
    } else {
      this.isEdit = false;
    }
  },
  methods: {
    hasRouteAuth,
    getDetail() {
      getEmoji({ id: this.orderId }).then(res => {
        if (res.data) {
          res.data.marketObj = {
            userName: res.data.market, id: res.data.marketId
          };
          res.data.clientObj = {
            clientName: res.data.clientName, id: res.data.clientId
          };
          if (res.data.licensePrice) {
            res.data.licensePrice = Number(res.data.licensePrice) / 100;
          }
          if (res.data.taxAmount) {
            res.data.taxAmount = Number(res.data.taxAmount) / 100;
          }
          if (res.data.materielPrice) {
            res.data.materielPrice = Number(res.data.materielPrice) / 100;
          }
          if (res.data.ipAry) {
            res.data.ipAry.forEach(j => {
              j.ipName = j.ipFigure;
              j.ipId = j.ipFigureId;
              j.ipNameAndSeries = `${j.ipFigure || '--'}/${j.ipSeries || '--'}`;
            });
          }
          if (res.data.deliveryTime && res.data.deliveryTime.toString().length === 10) {
            res.data.deliveryTime = res.data.deliveryTime * 1000;
          }
          if (res.data.orderTime && res.data.orderTime.toString().length === 10) {
            res.data.orderTime = res.data.orderTime * 1000;
          }
          // writeOffStatus 核销状态（0: '待核销', 1: '已完成', 2: '部分核销'）
          // 已完成和部分核销后不能编辑含税金额
          this.taxAmountDisabled = res.data.writeOffStatus === 1 || res.data.writeOffStatus === 2;
          // this.$refs.ipSupplier.initInfo(res.data.supplierAry); // 传值给成本信息
          if (this.$refs.costBreakdownRef && res.data.costBreakdown) this.$refs.costBreakdownRef.insertDetail(res.data.costBreakdown); // 传值给成本
          this.$nextTick(() => {
            if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(res.data.contract);
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceInfo);
          });
          this.paramsObj = res.data;
        }
      });
    },
    /**
     * 操作
     */
    toSubmit() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      if (paramsObj.deliveryTime && paramsObj.deliveryTime.toString().length === 13) paramsObj.deliveryTime = Math.floor(paramsObj.deliveryTime / 1000);
      if (paramsObj.orderTime && paramsObj.orderTime.toString().length === 13) paramsObj.orderTime = Math.floor(paramsObj.orderTime / 1000);
      const priceField = ['licensePrice', 'taxAmount', 'materielPrice']; // 价格的字段
      this.handelPrice(paramsObj, priceField);
      paramsObj.licensePrice = Number(paramsObj.licensePrice);
      paramsObj.taxAmount = Number(paramsObj.taxAmount);
      paramsObj.materielPrice = Number(paramsObj.materielPrice);
      // const supplierAry = this.$refs.ipSupplier.getParams();

      const discountInfoParams = this.$refs.costBreakdownRef ? this.$refs.costBreakdownRef.list : {};
      // discountInfoParams.costList.map(item => {
      //   item.taxCost = item.taxCost || item.taxCost === 0 ? item.taxCost * 100 : null;
      //   return item;
      // });
      paramsObj.costBreakdown = discountInfoParams;

      const relatedIds = this.getRelatedIds();
      paramsObj.invoiceIds = relatedIds.invoiceIds;
      paramsObj.contractIds = relatedIds.contractIds;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.edit(paramsObj);
          } else {
            this.add(paramsObj);
          }
        } else {
          return false;
        }
        // this.$refs['ipSupplier'].validateForm().then(res => { // 成本信息表单验证
        //   if (supplierAry === 'error') return;
        //   paramsObj.supplierAry = supplierAry;
        // });
      });
    },
    edit(params) {
      params.id = this.orderId;
      this.btnLoading = true;
      editEmojiOrder(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      createEmojiOrder(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 1;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    },
    handelPrice(params, priceField = []) {
      for (const key in params) {
        if (priceField.includes(key) && Number(params[key])) {
          const numberArr = params[key].toString().split('.');
          if (numberArr && numberArr.length) {
            if (numberArr.length === 1) { // 说明是整数，不用担心精度丢失
              params[key] = Number(params[key]) * 100;
            } else if (numberArr.length === 2) {
              let floatPart = numberArr[1];
              floatPart = floatPart.length >= 2 ? floatPart[0] + floatPart[1] : floatPart + 0;
              params[key] = Number(numberArr[0] + floatPart);
            }
          }
        }
      }
    },
    // 上传文件
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.paramsObj && this.paramsObj.attachment && this.paramsObj.attachment.length > 0) {
        this.paramsObj.attachment.unshift(fileList);
      } else {
        this.paramsObj.attachment = [fileList];
      }
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    /**
     * 获取下拉数据
     */
    // 获取ip形象
    getipFigure() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.ipName = '';
          if (params.userName) params.ipName = params.userName;
          getIpImageList(params).then(res => {
            if (res.data && res.data.items) {
              res.data.items.forEach(j => {
                if (!j.ipFigure)j.ipFigure = j.ipName;
                if (!j.ipFigureId)j.ipFigureId = j.ipId;
                j.ipNameAndSeries = `${j.ipName || '--'}/${j.ipSeriesName || '--'}`;
              });
            }
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    getClient() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.clientName = '';
          if (params.userName) params.clientName = params.userName;
          getClientList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    /**
     * change 事件
     */
    ipFigureChange(item) {
      // this.paramsObj.ipFigure = item.userName;
      // this.paramsObj.ipFigureId = item.id;
    },
    clientNameChange(item) {
      this.paramsObj.clientName = item.clientName;
      this.paramsObj.clientId = item.id;
    },
    marketChange(item) {
      this.paramsObj.market = item.userName;
      this.paramsObj.marketId = item.id;
    },
    numberInputChange(key) {
      if (this.paramsObj[key] || this.paramsObj[key] === 0) this.paramsObj[key] = Number(this.paramsObj[key]).toFixed(2);
      if (key === 'taxAmount' || key === 'licensePrice') {
        this.mathMaterielPrice();
        this.mathTaxAmount();
      }
    },
    mathMaterielPrice() {
      const taxAmount = this.paramsObj.taxAmount || 0;
      const licensePrice = this.paramsObj.licensePrice || 0;
      this.paramsObj.materielPrice = (taxAmount - licensePrice).toFixed(2);
    }, /**
     * 工具
     */
    mathTaxAmount() {
      const licensePrice = this.paramsObj.licensePrice;
      const incomeList = this.paramsObj.incomeList || [];
      if (incomeList.length === 0 && (!licensePrice && licensePrice !== 0)) {
        this.paramsObj.taxAmount = '';
        return;
      }
      let taxAmount = 0;
      incomeList.forEach(i => {
        if (i.totalPrice || i.totalPrice === 0) {
          taxAmount += Number(i.totalPrice);
        }
      });
      if (licensePrice || licensePrice === 0) {
        taxAmount += Number(licensePrice);
      }
      this.paramsObj.taxAmount = taxAmount.toFixed(2);
    },
    /**
     * 收入项
     */
    editIcomeItem(params) {
      editEmojiIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.freshIncomeData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    addIcomeItem(params) {
      params.mengliId = this.orderId;
      addEmojiIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.freshIncomeData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteIcomeItem(params) {
      deleteEmojiIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.freshIncomeData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    freshIncomeData() {
      getEmoji({ id: this.orderId }).then(res => {
        if (res.data) {
          this.paramsObj.incomeList = res.data.incomeList;
          this.mathTaxAmount();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-ip-order {
  background:rgba(255,255,255,1);
  padding: 24px;
  padding-bottom: 80px;
}
.create-ip-order-form {
  &::v-deep {
    .edit-order {
      display: flex;
      flex-wrap: wrap;
      .el-input {
        width: 240px;
      }
    }
    .el-form-item{
      margin-bottom: 24px;
    }
    .el-select__tags {
      display: flex;
      flex-wrap: wrap;
      .el-tag {
        max-width: 100%;
        display: flex;
        align-items: center;
        .el-select__tags-text {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
        }
        .el-tag__close {
          margin: 0;
          margin-right: 5px;
          flex-shrink: 0;
        }
      }
    }
    .el-range-editor {
      width: 240px;
      .el-range-input {
        width: 90px;
      }
      .el-range-separator {
        width:20px;
      }
    }
  }
  .left {
    margin-right: 108px;
  }
}
.one-cell {
  width: 100%;
  display: flex;
}
.create-ip-btn-container {
  margin-top: 40px;
}
.tip {
  position: absolute;
  right: 0;
}
.select-related-container {
  margin-top:30px;
   padding: 0;
  &::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
}

.fixed-foot {
  width: 100%;
  margin-bottom: 56px;
}
.tool-bar-container {
  position: fixed;
  bottom: 0px;
  height: 80px;
  right: 20px;
  width: 100%;
  z-index: 100;
  // background: linear-gradient(180deg, rgba(0,0,0,0), #fff,rgba(0,0,0,0));
  background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 56%, #FFFFFF 100%);
  border-radius: 0px 0px 8px 8px;
}
.container {
  // margin-bottom: 24px;
  // margin-top: 24px;
  width: 100%;
  border-radius: 0px 0px 8px 8px;
  display:flex;
  justify-content: center;
  bottom: 24px;
  position: absolute;
  &::v-deep {
    .el-button {
      margin-left: 16px;
    }
  }
}
</style>
<style lang="scss">
.create-ip-order-select {
    width: 240px;
}
</style>
